package com.yearner.reviewplan.common.model;

import com.alibaba.fastjson.JSON;
import com.yearner.reviewplan.common.enums.ResponseCode;
import com.yearner.reviewplan.common.exception.NormalException;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * @author pengyg
 * @since 2019/12/3
 */
@Getter
@Setter
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 257082057001832302L;

    private String message;
    private T data;
    private Integer code;
    private Integer totalCount;

    private Result() {
        message = "";
        data = null;
        code = 0;
    }

    private Result(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
    private Result(Integer code, String message, T data, Integer total) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.totalCount = total;
    }

    public static Result<String> success(String msg) {
        return new Result<>(ResponseCode.SUCCESS.getCode(), msg,null);
    }
    public static <T> Result<T> success(String msg,T data) {
        return new Result<>(ResponseCode.SUCCESS.getCode(), msg,data);
    }
    public static <T> Result<T> success(T data) {
        return new Result<>(ResponseCode.SUCCESS.getCode(), "OK",data);
    }
    public static <T> Result<T> success(T data, Integer total) {
        return new Result<>(ResponseCode.SUCCESS.getCode(), "OK",data,total);
    }

    public static Result<String> failed(int code, String msg) {
        return new Result<>(code, msg, null);
    }
    public static Result<String> failed(String msg) {
        return new Result<>(ResponseCode.FAILED.getCode(), msg, null);
    }
    public static <T> Result<T> failed(int code, String msg, T data) {
        return new Result<>(code, msg, data);
    }

    public static Result<String> success() {
        String msg = "OK";
        return new Result<>(ResponseCode.SUCCESS.getCode(),msg,null);
    }

    public static void error(String msg) {
        throw new NormalException(msg);
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
